<template>
  <div class="app-container">
    <div>
      <el-table :data="routes" :header-cell-style="{background:'#eef1f6',color:'#606266'}"
        style="width: 100%;margin-bottom: 20px;" row-key="id" border default-expand-all
        :tree-props="{children: 'children', hasChildren: 'hasChildren'}">
        <el-table-column label="权限名称">
          <template slot-scope="scope"><i :class="scope.row.meta.icon" :title="scope.row.meta.icon"></i>
            &nbsp;{{ scope.row.title }}</template>
        </el-table-column>
        <el-table-column label="权限标识">
          <template slot-scope="scope">{{ scope.row.code }}</template>
        </el-table-column>
        <el-table-column label="组件地址">
          <template slot-scope="scope">{{ scope.row.component }}</template>
        </el-table-column>
        <el-table-column label="跳转路径">
          <template slot-scope="scope">{{ scope.row.redirect }}</template>
        </el-table-column>
        <el-table-column align="center" label="操作" width="180">
          <template slot-scope="scope">
            <el-button type="text" size="mini" @click="handleUser(scope)" icon="el-icon-user">用户</el-button>
            <el-button type="text" size="mini" @click="handleRole(scope)" icon="el-icon-s-custom">角色</el-button>
          </template>
        </el-table-column>
      </el-table>

      <el-dialog :visible.sync="dialogUserVisible" :title="'分配用户'" :close-on-click-modal="false" width="60%" top="3vh">
        <div>
          <el-input v-model="userViewModel.UserName" size="small" placeholder="姓名" style="width: 200px;"
            class="filter-item" @keyup.enter.native="queryUser" />
          <el-input v-model="userViewModel.LoginName" size="small" placeholder="登录名" style="width: 200px;"
            class="filter-item" @keyup.enter.native="queryUser" />
          <el-input v-model="userViewModel.MobilePhone" size="small" placeholder="手机号" style="width: 200px;"
            class="filter-item" @keyup.enter.native="queryUser" />
          <el-button type="primary" @click="queryUser" size="small" icon="el-icon-search">查询</el-button>
          <el-button type="primary" @click="refreshUser" size="small" icon="el-icon-refresh">刷新</el-button>
        </div>
        <el-table v-loading="loading" :header-cell-style="{background:'#eef1f6',color:'#606266'}" :data="userList"
          style="width: 100%;margin-top:30px;" border @sort-change="sortChange" ref="multipleTable"
          @selection-change="handleSelectionChange">
          <el-table-column type="selection" width="55">
          </el-table-column>
          <el-table-column label="姓名" sortable="custom" prop="UserName">
            <template slot-scope="scope">{{ scope.row.UserName }}</template>
          </el-table-column>
          <el-table-column label="登录名" sortable="custom" prop="LoginName">
            <template slot-scope="scope">{{ scope.row.LoginName }}</template>
          </el-table-column>
          <el-table-column label="手机号" sortable="custom" prop="MobilePhone">
            <template slot-scope="scope">{{ scope.row.MobilePhone }}</template>
          </el-table-column>
        </el-table>
        <!-- 分页组件：https://element.eleme.cn/#/zh-CN/component/pagination -->
        <div class="block" style="float:right;margin-top:15px;" v-if="userViewModel.total>0">
          <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
            :current-page="userViewModel.page" :page-sizes="[10, 20, 30, 40,100]" :page-size="userViewModel.pageSize"
            @prev-click="lastPage" @next-click="nextPage" background layout="total, sizes, prev, pager, next, jumper"
            :total="userViewModel.total"></el-pagination>
        </div>
        <div style="text-align:right;margin-top: 60px;">
          <el-button type="danger" @click="dialogUserVisible=false">关闭</el-button>
          <el-button type="primary" @click="confirmAuthUser">确认</el-button>
        </div>
      </el-dialog>

      <el-dialog :visible.sync="dialogRoleVisible" :title="'分配角色'" :close-on-click-modal="false" width="60%" top="3vh">
        <el-form :model="model" ref="model" label-width="100px" label-position="right">
          <el-form-item label="权限名称" prop="title">
            <el-input v-model="model.title" placeholder="权限名称" :disabled="true" />
          </el-form-item>
          <el-form-item label="菜单">
            <el-tree ref="tree" :data="rolesList" :props="defaultProps" show-checkbox default-expand-all node-key="id"
              class="permission-tree" />
          </el-form-item>
        </el-form>
        <div style="text-align:right;margin-top: 60px;">
          <el-button type="danger" @click="dialogRoleVisible=false">关闭</el-button>
          <el-button type="primary" @click="confirmAuthRole">确认</el-button>
        </div>
      </el-dialog>
    </div>
  </div>
</template>

<script>
  import { deepClone } from "@/utils";
  import { getRoutes, getMenuUser, handleMenuUser, getMenuRole, handleMenuRole } from "@/api/menu";
  import { getUserList } from '@/api/user'
  import { getRoleList } from "@/api/role";

  const defaultModel = {
    id: "",
    parentId: "",
    parentName: "",
    component: "",
    name: "",
    title: "",
    code: "",
    type: 1,
    path: "",
    redirect: "",
    sort: 0,
    hasChildren: false,
    meta: {
      title: "",
      roles: [
      ],
      affix: "",
      nocache: "",
      icon: ""
    },
    hidden: false,
    children: [
    ]
  };

  export default {
    data() {
      return {
        filterText: '',
        model: Object.assign({}, defaultModel),
        routes: [],
        userList: [],
        rolesList: [],
        multipleSelection: [],
        dialogVisible: false,
        dialogType: "new",
        dialogUserVisible: false,
        dialogRoleVisible: false,
        loading: true,
        roleViewModel: {
          page: 1,
          pageSize: 10,
          total: 0,
          RoleName: '',
          OrderBy: 'CreateTime',
          IsAsc: ''
        },
        userViewModel: {
          page: 1,
          pageSize: 10,
          total: 0,
          UserName: '',
          LoginName: '',
          MobilePhone: '',
          UserType: '',
          OrderBy: 'UserID',//排序字段
          SortDir: '' //是否升序
        },
        typeOptions: [1, 2],
        defaultProps: {
          children: "children",
          label: "RoleName"
        },
        labelPosition: 'right'
      };
    },
    created() {
      this.getRoutes()
      this.queryUser()
      this.queryRole()
    },
    methods: {
      async getRoutes() {
        const res = await getRoutes();
        this.routes = res.data;
      },
      refresh() {
        this.getRoutes()
      },
      handleUser(scope) {
        this.dialogUserVisible = true
        this.model = deepClone(scope.row)
        getMenuUser(scope.row.id).then(res => {
          this.multipleSelection = res.data
          this.toggleSelection(this.multipleSelection)
        })
      },
      async getUserList(userViewModel) {
        this.loading = true;
        const res = await getUserList(userViewModel);
        if (res.data) {
          this.userViewModel.total = res.data.TotalCount;
        }
        this.userList = res.data.UserItems;
        this.loading = false;
      },
      queryUser() {
        this.userViewModel.page = 1;
        this.getUserList(this.userViewModel);
      },
      refreshUser() {
        this.userViewModel.UserName = '';
        this.userViewModel.LoginName = '';
        this.userViewModel.MobilePhone = '';
        this.userViewModel.OrgCode = '';
        this.userViewModel.OrgName = '';
        this.userViewModel.page = 1;
        this.getUserList(this.userViewModel);
      },
      sortChange(data) {
        const { prop, order } = data
        this.userViewModel.OrderBy = prop
        if (prop == null || prop == "")
          this.userViewModel.OrderBy = "UserID"
        if (order === 'ascending') {
          this.userViewModel.SortDir = 'asc'
        } else {
          this.userViewModel.SortDir = 'desc'
        }
        this.queryUser()
      },
      lastPage(val) {
        this.userViewModel.page = val;
      },
      nextPage(val) {
        this.userViewModel.page = val;
      },
      handleSizeChange(val) {
        this.userViewModel.pageSize = val;
        this.getUserList(this.userViewModel);
      },
      handleCurrentChange(val) {
        this.userViewModel.page = val
        this.getUserList(this.userViewModel);
      },
      handleSelectionChange(val) {
        this.multipleSelection = val; // list<user>
      },
      toggleSelection(rows) {
        this.$refs.multipleTable.clearSelection();
        if (rows) {
          rows.forEach(row => {
            var p = this.userList.filter(u => u.LoginName == row)[0]
            this.$refs.multipleTable.toggleRowSelection(p, true);
          });
        } else {
          this.$refs.multipleTable.clearSelection();
        }
      },
      async confirmAuthUser() {
        await handleMenuUser({ MenuId: this.model.id, Users: this.multipleSelection })
        this.$notify({
          title: "成功",
          type: "success",
          message: "操作成功!"
        });
        this.dialogUserVisible = false
      },
      handleRole(scope) {
        this.dialogRoleVisible = true
        this.model = deepClone(scope.row)
        getMenuRole(scope.row.id).then(res => {
          this.$nextTick(() => {
            this.$refs.tree.setCheckedKeys(res.data);
          });
        })
      },
      async getRoles(roleViewModel) {
        this.loading = true;
        const res = await getRoleList(roleViewModel);
        if (res.data) {
          this.roleViewModel.total = res.data.Total;
        }
        this.rolesList = res.data.Items;
        this.loading = false;
      },
      queryRole() {
        this.roleViewModel.page = 1 
        this.getRoles(this.roleViewModel);
      },
      async confirmAuthRole() {
        await handleMenuRole({ MenuId: this.model.id, RoleIds: this.$refs.tree.getCheckedKeys() })
        this.$notify({
          title: "成功",
          type: "success",
          message: "操作成功!"
        });
        this.dialogRoleVisible = false
      }
    }
  };
</script>

<style scoped>
  .custom-tree-node {
    flex: 1;
    display: flex;
    align-items: center;
    justify-content: space-between;
    font-size: 14px;
    padding-right: 12px;
  }
</style>